/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.utils
{
	import com.edi.proxy.component.HttpProxy;
	import com.edi.proxy.component.HttpProxyResult;
	import com.edi.proxy.component.SPOParam;
	import com.edi.runtime.component.EDIAlert;
	import com.edi.runtime.component.EDIApplication;
	import com.edi.runtime.component.EDIDataGrid;
	import com.edi.runtime.component.EDIDataGridColumn;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	
	/**
	 * 导出Excel的工具类.
	 * 
	 */	
	public class ExportExcelUtils
	{
		private var fileRef:FileReference;
		
		public function ExportExcelUtils()
		{
		}

		/**
		 * 导出服务的公有方法  
		 * @param datagrid   需要导出的列表对象
		 * @param sqlinfo    导出需要的sql脚本
		 * @param fileName   需要保存的文档名称
		 * @param sheetname  文档内的标签名称
		 * @param title      文档的标题
		 * @param serverPath 导出的文件在服务器上存放的路径,默认为UserFiles下.可自定义,如"UserFiles\\File\\file",但需要保证该路径在服务器上真实存在.
		 * 
		 */		
		public  function buildExcelBySql(datagrid:EDIDataGrid,sqlinfo:String, fileName:String="文档名称", sheetname:String="标签名称", title:String="标题名称", serverPath:String="UserFiles"):void
		{
			if(!sqlinfo){
				return;
			}
			if(!datagrid.dataProvider){
				return;
			}
			var array:Array=datagrid.columns;
			var headArray:Array=new Array();
			var headTextXmllist:XML=new XML(<row></row>);
			for (var i:int=0; i < array.length; i++)
			{
				var dc:EDIDataGridColumn = array[i] as EDIDataGridColumn;
				headArray.push(dc.dataField + ":" + dc.headerText);
			}
			exportExcelSql(sqlinfo, headArray.join(";"), fileName, serverPath, title, sheetname);
		}
		
		/**
		 * DataGrid的导出功能,该功能共需要四个参数,见参数说明. 
		 * @param fileName   导出的文档名称
		 * @param sheetname  导出的excel的标签名称
		 * @param title      导出的excel的标题
		 * @param serverPath 导出的文件在服务器上存放的路径,默认为UserFiles下.可自定义,如"UserFiles\\File\\file",但需要保证该路径在服务器上真实存在.
		 * 
		 */		
		public function buildExcelByData(datagrid:EDIDataGrid,fileName:String="文档名称",sheetname:String="标签名称",title:String="标题名称",serverPath:String="UserFiles"):void{
			var array:Array = datagrid.columns;
			var headTextXmllist:XML = new XML(<row></row>);
			for(var i:int=0;i<array.length;i++){
				var dc:EDIDataGridColumn = array[i] as EDIDataGridColumn;
				headTextXmllist[dc.dataField] = dc.headerText;
			}
			var dataxmllist:XMLList = XMLList(datagrid.dataProvider);
			var str:String ="<table filename='"+fileName+"' sheetname='"+sheetname+"' title='"+title+"'>"+ headTextXmllist.toString()+dataxmllist.toString()+"</table>";
			
			exportExcel(fileName,str,serverPath);
		}
		
//		/**
//		 * 导出服务的公有方法  
//		 * @param datagrid   需要导出的列表对象
//		 * @param sqlinfo    导出需要的sql脚本
//		 * @param fileName   需要保存的文档名称
//		 * @param sheetname  文档内的标签名称
//		 * @param title      文档的标题
//		 * @param serverPath 导出的文件在服务器上存放的路径,默认为UserFiles下.可自定义,如"UserFiles\\File\\file",但需要保证该路径在服务器上真实存在.
//		 * 
//		 */		
//		public  function buildExcelBySqlOfBopDatagrid(datagrid:BOPSDataGrid,sqlinfo:String, fileName:String="文档名称", sheetname:String="标签名称", title:String="标题名称", serverPath:String="UserFiles"):void
//		{
//			if(!sqlinfo){
//				return;
//			}
//			if(!datagrid.dataProvider){
//				return;
//			}
//			var array:Array=datagrid.columns;
//			var headArray:Array=new Array();
//			var headTextXmllist:XML=new XML(<row></row>);
//			for (var i:int=0; i < array.length; i++)
//			{
//				var dc:EDIDataGridColumn = array[i] as EDIDataGridColumn;
//				headArray.push(dc.dataField + ":" + dc.headerText);
//			}
//			exportExcelSql(sqlinfo, headArray.join(";"), fileName, serverPath, title, sheetname);
//		}
//		
//		/**
//		 * DataGrid的导出功能,该功能共需要四个参数,见参数说明. 
//		 * @param fileName   导出的文档名称
//		 * @param sheetname  导出的excel的标签名称
//		 * @param title      导出的excel的标题
//		 * @param serverPath 导出的文件在服务器上存放的路径,默认为UserFiles下.可自定义,如"UserFiles\\File\\file",但需要保证该路径在服务器上真实存在.
//		 * 
//		 */		
//		public function buildExcelByDataOfBopDatagrid(datagrid:BOPSDataGrid,fileName:String="文档名称",sheetname:String="标签名称",title:String="标题名称",serverPath:String="UserFiles"):void{
//			var array:Array = datagrid.columns;
//			var headTextXmllist:XML = new XML(<row></row>);
//			for(var i:int=0;i<array.length;i++){
//				var dc:EDIDataGridColumn = array[i] as EDIDataGridColumn;
//				headTextXmllist[dc.dataField] = dc.headerText;
//			}
//			var dataxmllist:XMLList = XMLList(datagrid.dataProvider);
//			var str:String ="<table filename='"+fileName+"' sheetname='"+sheetname+"' title='"+title+"'>"+ headTextXmllist.toString()+dataxmllist.toString()+"</table>";
//			
//			exportExcel(fileName,str,serverPath);
//		}
		
		
		private function exportExcel(fileName:String,str:String,serverPath:String){
			var spo:SPOParam = new SPOParam();
			spo.serviceName = "ServicesExportExcelForDataGrid.serviceExportExcel";
			var s1 = BOPStringUtils.replace(str,"<![CDATA[",">");
			var s2 = BOPStringUtils.replace(s1,"]]>","");	
			spo.addParameters("dataInfo",s2);
			spo.addParameters("serverpath",serverPath);
			spo.dsName = "exportdatainfos_hrsoft";
			var hp:HttpProxy = new HttpProxy(EDIApplication.appName);
			hp.addPoParam(spo);
			hp.send();
			hp.resultCallback = function(e:HttpProxyResult):void{
				var result:String = e.getPoResultByDsName("exportdatainfos_hrsoft").object.String;
				Alert.yesLabel = "确定";
				Alert.cancelLabel = "取消";
				EDIAlert.show("导出成功,是否下载?","温馨提示",Alert.YES|Alert.CANCEL,null,function(ce:mx.events.CloseEvent):void{
					if(ce.detail == Alert.YES){
						download(fileName,result,serverPath);
					}
				},null,Alert.YES);
				
			};
		}
		
		//以下为通过sql语句导出excel文件调用服务方法
		private function exportExcelSql(sqlinfo:String, headText:String, fileName:String, serverPath:String, title:String, sheetname:String)
		{
			var spo:SPOParam=new SPOParam();
			spo.serviceName="ServicesExportExcelForDataGrid.serviceExportExcelBySql";
			spo.addParameters("sqlinfo", sqlinfo);
			spo.addParameters("headText", headText);
			spo.addParameters("appname", EDIApplication.appName);
			spo.addParameters("serverpath", serverPath);
			spo.addParameters("sheetname", sheetname);
			spo.addParameters("title", title);
			spo.dsName="exportdatainfos_hrsoft_sql";
			var hp:HttpProxy=new HttpProxy(EDIApplication.appName);
			hp.addPoParam(spo);
			hp.send();
			hp.resultCallback=function(e:HttpProxyResult):void
			{
				var result:String=e.getPoResultByDsName("exportdatainfos_hrsoft_sql").object.String;
				Alert.yesLabel="确定";
				Alert.cancelLabel="取消";
				EDIAlert.show("导出成功,是否下载?", "温馨提示", Alert.YES | Alert.CANCEL, null, function(ce:mx.events.CloseEvent):void
					{
						if (ce.detail == Alert.YES)
						{
							download(fileName, result, serverPath);
						}
					}, null, Alert.YES);

			};
		}
		
		private function download(downFileName:String,serverFileName:String,serverPath:String):void{
			var filename:String;
			var fileurl:String = EDIApplication.path + serverPath+"/"+serverFileName+".xls";
			var filename:String =  downFileName;
			fileRef = new FileReference();
			fileRef.addEventListener(Event.COMPLETE,completeHandler);
			fileRef.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
			fileRef.download(new URLRequest(fileurl),filename);
		}

		private function completeHandler(e:Event):void{	
			EDIAlert.show("下载成功！","温馨提示");
		}

		private function errorHandler(e:Event):void{	
			EDIAlert.show("下载失败！请检查网络连接重试！","温馨提示");
		}
	}
}